import Component from "../../../../wxsys/lib/base/component";

function request(option) {
    return new Promise(function(resolve, reject) {
        option = option || {};
        option.success = function(res) {
            resolve(res);
        };
        option.fail = function(error) {
            reject(error);
        };
        wx.request(option);
    });
}

export default class Wxtemplate extends Component {
	constructor(page, id, props, context) {
        super(page, id, props, context);
    }
    
    pushTemplateMsg(args,url,params) {
    	if(args && typeof args == "string"){
    		args = {
    			formId:args,
    			url:url,
    			params:params
    		};
    	}
    	var self = this;
    	//推送前
        this.fireEvent('pushBefore', {
            source: this
        });
		
		console.log(self);
		
        //获取发送模板消息需要的formId
        var formId = args.formId;
        var options = {};
        var data = [];
		var templateId = this.props.templateId;
		var page = args.url||null;
		var pageParams = args.params||null;
		var emphasisKeyword = this.props.emphasisKeyword;
		var keyword1 = this.props.one;
		var keyword2 = this.props.two;
		var keyword3 = this.props.three;
		var keyword4 = this.props.four;
		var keyword5 = this.props.five;
		var keyword6 = this.props.six;
		var keyword7 = this.props.seven;
		var keyword8 = this.props.eight;
		var keyword9 = this.props.nine;
		var keyword10 = this.props.ten;
		var toUser = this.props.toUser;
		if(templateId) {
			options.templateId = templateId.split(":")[1];
            if(options.templateId===undefined || options.templateId.length===0){
                this.page.hint('模板消息必须选择！');
                return;
            }
		}else {
			this.page.hint('请选择模板消息！');
            return;
		}
		if(page) {
			page = page.replace("$UI/", "");
			page = page.replace(".w", "");
			var params = "";
			if(pageParams) {
				var keys = Object.keys(pageParams);
				for(var i=0;i<keys.length;i++) {
					params += keys[i]+"=";
					var value = pageParams[keys[i]];
					if(value && value !== "undefined") {
						params += value;
					}
					if(i<keys.length-1) {
						params += "&";
					}
				}
				page = page+"?"+params;
			}
			options.page = page;
		}
		options.color = "";
		if(emphasisKeyword) {
			options.emphasisKeyword = emphasisKeyword +".DATA";
		}
		if(toUser) {
			options.toUser = this.page[this.props.$executeExprBinding_toUser](this.context.vars) || this.props.toUser;
		}
		//关键词对应的颜色官方已经废弃，传递进去也没有用
		if(keyword1) {
			data.push({"name":"keyword1","value":this.page[this.props.$executeExprBinding_one](this.context.vars) || this.props.one,"color":""});//,"color":this._getValue(keyword1Color)
		}
		if(keyword2) {
			data.push({"name":"keyword2","value":this.page[this.props.$executeExprBinding_two](this.context.vars) || this.props.two,"color":""});
		}
		if(keyword3) {
			data.push({"name":"keyword3","value":this.page[this.props.$executeExprBinding_three](this.context.vars) || this.props.three,"color":""});
		}
		if(keyword4) {
			data.push({"name":"keyword4","value":this.page[this.props.$executeExprBinding_four](this.context.vars) || this.props.four,"color":""});
		}
		if(keyword5) {
			data.push({"name":"keyword5","value":this.page[this.props.$executeExprBinding_five](this.context.vars) || this.props.five,"color":""});
		}
		if(keyword6) {
			data.push({"name":"keyword6","value":this.page[this.props.$executeExprBinding_six](this.context.vars) || this.props.six,"color":""});
		}
		if(keyword7) {
			data.push({"name":"keyword7","value":this.page[this.props.$executeExprBinding_seven](this.context.vars) || this.props.seven,"color":""});
		}
		if(keyword8) {
			data.push({"name":"keyword8","value":this.page[this.props.$executeExprBinding_eight](this.context.vars) || this.props.eight,"color":""});
		}
		if(keyword9) {
			data.push({"name":"keyword9","value":this.page[this.props.$executeExprBinding_nine](this.context.vars) || this.props.nine,"color":""});
		}
		if(keyword10) {
			data.push({"name":"keyword10","value":this.page[this.props.$executeExprBinding_ten](this.context.vars) || this.props.ten,"color":""});
		}
		if(data.length === 0) {
			this.page.hint('模板消息对应的关键词内容不能为空！');
            return;
		}
		options.data = data;
		console.log(options);

		if('the formId is a mock one' === formId || !formId) {	
			formId = args.prepayId;
        }
		if(!formId) {
			this.page.hint('invalid formId');
			return;
		}
		options.formId = formId;
		request({
            url: wx.App.baseUrl + '/wxapi/miniapp/template',
            method: 'POST',
            data: JSON.stringify(options),
            header: {
                'content-type': 'application/json;charset=UTF-8'
            }
        }).then((res) => {
        	//模板消息推送成功
        	if(res.data.success) {
        		self.fireEvent('pushSuccess', {
                    source: self
                });
        	}else {//模板消息推送失败
        		self.page.hint(res.data.msg);
        		self.fireEvent('pushFail', {
                    source: self
                });
        	}
        });
		
    }
	
    initOperation() {
        super.initOperation();
        var operations = {
            'pushTemplateMsg': {
                label: "消息推送",
                argsDef: [],
                method: function(args) {
                	if(!args.formId){
                		try {
    						args.formId = arguments[1].$event.detail.formId;
    					} catch (error) {
    						args.formId = "";
    					}
                	}
                    return this.owner.pushTemplateMsg(args);
                }
            }

        };

        for (let name in operations)
            this.defineOperation(name, operations[name]);
    }
}

wx.comp = wx.comp || {};
wx.comp.Wxtemplate = Wxtemplate;